import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver import Keys
from selenium.common.exceptions import SessionNotCreatedException
import subprocess
import socket
import psutil
import requests
import json
import time

def kill(app):
    

    # 要结束的进程名称（不包括.exe）
    process_name = app

    # 查找进程
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == process_name:
            # 结束进程
            psutil.Process(proc.info['pid']).kill()
            print(f"Process {process_name} with PID {proc.info['pid']} has been terminated.")


#选择浏览器
def choose_browser(browser='Firefox'):
    if browser=='Firefox':
        
        #到这里下载最新火狐浏览器"https://www.mozilla.org/zh-CN/firefox/all/desktop-release/win64-msi/zh-CN/"
        #下面是firefox接管已打开网页的方法，调试时使用
        
        #"C:\Program Files\Mozilla Firefox\firefox.exe" -marionette -start-debugger-server 2828
        command = '"C:\\Program Files\\Mozilla Firefox\\firefox.exe"'
        command1=command+' -marionette -start-debugger-server 2828'
        if not test_port('127.0.0.1',2828):
            print('马上打开firefox机器调试模式')
            
            subprocess.Popen(command1)
        else:
            print('2828端口畅通，firefox已开启了机器调试模式')


        #firefox_services = Service(executable_path='C:/py/0929/geckodriver.exe',port=3000,service_args=['--marionette-port', '2828', '--connect-existing'])
        firefox_services = Service(executable_path=executable_path,port=3000,service_args=['--marionette-port', '2828', '--connect-existing'])
        #driver = webdriver.Firefox(service=firefox_services)
        #driver.close()
        try:
            return webdriver.Firefox(service=firefox_services)
        except SessionNotCreatedException as e:
            print("无法创建新的会话，可能是因为会话已经存在。错误信息：", e)
            print('正在尝试杀掉geckodriver.exe，重启firefox')
            kill('geckodriver.exe')
            return webdriver.Firefox(service=firefox_services)
        
    #driver = webdriver.Firefox(executable_path='C:\py\1006\geckodriver-0.35.0')
    if browser=='Chrome':
        # 创建 Options 选项对象
        opt = Options()
        opt.binary_location = r'C:\Program Files\Google\Chrome\Application\chrome.exe'	# 指定 Chrome 浏览器的路径

        # 创建 Service 对象
        ser = Service()	
        ser.executable_path = r'C:\Program Files\Python312\chromedriver.exe'	# 指定 ChromeDriver 的路径
        chrome_location=r"C:\Program Files\Google\Chrome\Application\chrome.exe"
        '''
        
##        #open_chrome_command=chrome_location+' --remote-debugging-port=9222 --user-data-dir="c:\temp"'
##
##        open_chrome_command=chrome_location+' --remote-debugging-port=9222'
##        print(open_chrome_command)
##        command = '"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe"'
##        command1=command+' --remote-debugging-port=9222'
##        print(command1)
##        print(command)
##
##        # 运行命令
##        #os.system(command1)
##        subprocess.Popen(command1)
        '''
        return webdriver.Chrome(options=opt)

#选中元素的xpath并点击
def click1(xpath,comments=''):
    if wait0(xpath):
        print(xpath,'click',comments)
        element = driver.find_element(By.XPATH, xpath)
        element.click()
        time.sleep(1)
#选中输入框的xpath并输入text    
def input1(xpath,text):
    if wait0(xpath):
        print(xpath,text)
        element = driver.find_element(By.XPATH, xpath)
        print('准备输入文本：',text)
        #time.sleep(1)
        element.send_keys(text)
        #time.sleep(1)

#等待元素出现
def wait0(xpath,comments='',max_attempts=3):
    print(xpath,comments)

    try:
        element = driver.find_element(By.XPATH, xpath)
        print(xpath,'已出现')
        return True
    except:
        print('waiting ......')
        if max_attempts > 0:
            time.sleep(5)
        
        
            wait0(xpath, comments, max_attempts - 1)
        else:
            print('已尝试n次，元素仍未出现。')
            driver.close()
            return False
        
#打开网页        
def open1(link,comments=''):
    print(comments,link)
    driver.get(link)
    time.sleep(2)

#获取xpath的文字
def get_text(xpath):
    #xpath='//*[@id="main_price"]/em'
    element = driver.find_element(By.XPATH, xpath)
    print('价格是',element.text)
    return element.text

#测试端口是否通
def test_port(ip, port):
    try:
        socket.create_connection((ip, port), timeout=1).close()
        print(ip,port,'端口通')
        return True
    except socket.error as e:
        print(f"Port {port} is not available.")
        return False

def get_latest_message(room_id):
    try:
        url='https://api.live.bilibili.com/xlive/web-room/v1/dM/gethistory?roomid='
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
            'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
            'Accept-Language': 'en-US,en;q=0.5',
            'Connection': 'keep-alive',
            # 可以添加更多需要的头部信息
        }
        print('*',url+room_id)
        
        response = requests.get(url+room_id, headers=headers)
        print('**',response)
        data =json.loads(response.text)
        #print(data)
        len0=len(data['data']['room'])
        text=data['data']['room'][len0-1]['text']
        print(len0,text)
        if text is None:
            text='你好呀'

        return text
    except:
        time.sleep(3)
        get_latest_message(room_id)

def hailuo_search_and_play_latest(message):
    #//*[@id="chat-input-box"]
    #//*[@id="chat-input"]
    input_xpath='//*[@id="chat-input"]'
    input1(input_xpath,message)
    input1(input_xpath,Keys.ENTER)
    elements=driver.find_elements(By.CSS_SELECTOR, ".ml-3")
    len0=len(elements)
    mode=0
    for _ in range(20):
        if mode ==0:
            time.sleep(2)
            elements=driver.find_elements(By.CSS_SELECTOR, ".ml-3")
            len1=len(elements)
            
            if len1==len0:
                print('未完成，请等待')
            
            else:
                mode=1
                break
    
    element = elements[-1]
    element.click()

def mark_red(element):
        # 获取元素的引用
    element_ref = driver.execute_script("return arguments[0]", element)

    # 使用JavaScript来高亮显示元素
    driver.execute_script("""
        var element = arguments[0];
        element.style.border = '3px solid red'; // 设置边框为红色高亮显示
    """, element_ref)

        
if __name__ == "__main__":
    print('start')
    #下载firfox的geckodriver驱动
    #https://github.com/mozilla/geckodriver/releases
    #名字叫geckodriver-v0.35.0-win32.zip
    #解压到自己计算机的制定位置,注意位置是双斜杠，改成自己的geckodriver.exe路径
    executable_path='./geckodriver.exe'
    
    #选择浏览器并打开，默认是火狐
    driver = choose_browser()


    
    #open('https://plogin.m.jd.com/login/login?')
    #海螺ai
    link='https://hailuoai.com/?type=chat&chatID=299481585525055490'
    #link='https://www.baidu.com'
    open1(link)

    
      
    
    print(driver.title)


    #print('xxxxxxxxx',element[0])



    
    #elements = driver.find_elements_by_css_selector(".p-0.5")
    

    # 如果列表中至少有两个元素，获取倒数第二个元素
    #if len(elements) >= 2:
    #    second_last_element = elements[-2]
    #click1(path1)
    #element = driver.find_element_by_xpath()

    #print(element)

    
    #driver.quit()
    #wait0('//*[@id="msShortcutMenu"]/span')
    #open('https://item.m.jd.com/product/10086891405101.html')
    #get_text('//*[@id="main_price"]/em')
    room_id='31787907'
    #room_id='23145747'

    for i in range(5000):
    
        last_message=get_latest_message(room_id)
        time.sleep(5)
        current_message=get_latest_message(room_id)
        print(last_message,current_message)
        if current_message==last_message:
            print('无新留言')
        else:
            print('有新留言',current_message)
            hailuo_search_and_play_latest(current_message)
    driver.close()
